package com.app.oral.service.impl

import com.app.oral.dao.UserSessionMapper
import com.app.oral.model.UserSession
import com.app.oral.service.UserSessionService
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.util.*

@Service
class UserSessionServiceImpl(
    private val userSessionMapper: UserSessionMapper
) : UserSessionService {

    companion object {
        // 会话有效期：7天
        const val SESSION_EXPIRE_DAYS = 7L
    }

    /**
     * 创建用户会话
     */
    override fun createSession(userId: Long, openid: String): UserSession {
        // 生成唯一的会话令牌
        val sessionKey = generateSessionToken()
        val accessToken = generateSessionToken()
        val refreshToken = generateSessionToken()
        val now = LocalDateTime.now()
        val expiresTime = now.plusDays(SESSION_EXPIRE_DAYS)

        val session = UserSession(
            userId = userId,
            openid = openid,
            sessionKey = sessionKey,
            accessToken = accessToken,
            refreshToken = refreshToken,
            isActive = true,
            createdTime = now,
            lastAccessTime = now,
            expiresTime = expiresTime
        )

        userSessionMapper.insert(session)
        return session
    }

    /**
     * 验证会话是否有效
     */
    override fun validateSession(sessionKey: String): UserSession? {
        return userSessionMapper.findBySessionKey(sessionKey)
    }

    /**
     * 更新会话访问时间
     */
    override fun updateSessionAccess(sessionKey: String) {
        userSessionMapper.updateLastAccessTime(sessionKey)
    }

    /**
     * 用户登出（失效所有会话）
     */
    override fun logout(userId: Long): Boolean {
        return userSessionMapper.deactivateByUserId(userId) > 0
    }

    /**
     * 根据openid登出
     */
    override fun logoutByOpenid(openid: String): Boolean {
        return userSessionMapper.deactivateByOpenid(openid) > 0
    }

    /**
     * 失效指定会话
     */
    override fun deactivateSession(sessionKey: String): Boolean {
        return userSessionMapper.deactivateSession(sessionKey) > 0
    }

    /**
     * 检查用户是否已有活跃会话
     */
    override fun hasActiveSession(openid: String): UserSession? {
        val activeSessions = userSessionMapper.findByOpenid(openid)
        return activeSessions.firstOrNull()
    }

    /**
     * 清理过期会话
     */
    override fun cleanExpiredSessions(): Int {
        return userSessionMapper.deleteExpiredSessions()
    }

    /**
     * 生成会话令牌
     */
    private fun generateSessionToken(): String {
        return UUID.randomUUID().toString().replace("-", "") + 
               System.currentTimeMillis().toString(36)
    }
}